package com.wang.myblog.controller;

import com.alibaba.fastjson.JSONObject;
import com.wang.myblog.common.PageRequest;
import com.wang.myblog.common.PageResponse;
import com.wang.myblog.common.ResponseResult;
import com.wang.myblog.entity.*;
import com.wang.myblog.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ArticleController {


    @Autowired
    private ArticleService articleService;

    @Autowired
    private KindService kindService;

    @Autowired
    private TagService tagService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private CommentService commentService;

    /**
     * 展示文章
     * @param model
     * @return
     */
    @RequestMapping("/article")
    public String article( Model model, Integer articleId){

        // 获取指定的文章
        Article article = articleService.queryById(articleId);

        Admin user=adminService.queryById(1);
        user.setPassword(null);

        // 获取所有标签
        List<Tag> tags  = tagService.queryAll();
        // 获取所有的文集
        List<Kind> kinds = kindService.queryAll();
        // 获取阅读量最高的10篇文章
        List<Article> famousArticles = articleService.queryOrderByReadCount();
        //获取日期归档
        List<Archive> archives=articleService.getArchive();
        // 获取所有的评论
        List<Comment> comments = commentService.queryByArticleIdAndType(articleId, 0);
        model.addAttribute("article",article);
        // System.out.println(article);
        model.addAttribute("user",user);
        model.addAttribute("tags",tags);
        model.addAttribute("kinds",kinds);
        model.addAttribute("famousArticles",famousArticles);
        model.addAttribute("archives",archives);
        model.addAttribute("comments",comments);
        article.setReadCount(article.getReadCount()+1);
        articleService.update(article);
        return "front/article";
    }


    /**
     * 前往发布文章的界面
     * @param model
     * @return
     */
    @RequestMapping("/publishArticle")
    public String semo(Model model){
        List<Kind> kinds=kindService.queryAll();
        model.addAttribute("kinds",kinds);
        List<Tag> tags=tagService.queryAll();
        model.addAttribute("tags",tags);
        return "admin/new";
    }

    /**
     * 发布文章或者放入回收站
     * @param obj
     * @return
     */
    @RequestMapping("/publish")
    @ResponseBody
    //String title,String content,String introduce,String articleCoverImg  不用json传参数情况
    public String publish(@RequestBody JSONObject obj){
        List<Integer> tagIdList=obj.getJSONArray("tags").toJavaList(Integer.class);
        ResponseResult result=new ResponseResult();
        //这里的Id是文章的Id
        //Integer id = articleService.publish(title, content,introduce,1,articleCoverImg);
        Integer id = articleService.publish(obj.getString("title"), obj.getString("content"), obj.getString("introduce"), obj.getInteger("status"), obj.getString("img"),obj.getInteger("kindId"),tagIdList);
        result.setCode(200);
        result.setData(id);
        result.setMessage("成功");
        result.setUrl("urlrlrlr");
        return JSONObject.toJSONString(result);
    }

    /**
     * 前往文章管理界面（已发布的文章）
     * @return
     */
    @RequestMapping("/publishedArticleManage")
    public String publishedArticleManage(){

        return "admin/publish";
    }

    /**
     * 获取已发布文章的信息
     * @param request
     * @return
     */
    @PostMapping("/publishedArticleInfo")
    @ResponseBody
    public PageResponse publishedArticle1(@RequestBody PageRequest request){
        request.setSearchMsg(request.getSearchMsg().replace(" ",""));
        if (request.getSearchMsg().equals(""))
            request.setSearchMsg(null);
        PageResponse pageResponse=articleService.queryByPageAndStatus(request.getDraw(),request.getOffset(), request.getPageSize(), 1, request.getSearchMsg());
        List<Article> list=(List<Article>) pageResponse.getData();

        return pageResponse;
    }

    /**
     * 前往文章管理界面（回收站里的文章）
     * @return
     */
    @RequestMapping("/recycledArticleManage")
    public String recycledArticleManage(){
        return "admin/recycle";
    }

    /**
     * 获取回收站里文章的信息
     * @param request
     * @return
     */
    @PostMapping("recycledArticleInfo")
    @ResponseBody
    public PageResponse recycledArticleInfo(@RequestBody PageRequest request){

        request.setSearchMsg(request.getSearchMsg().replace(" ",""));
        if (request.getSearchMsg().equals(""))
            request.setSearchMsg(null);
        PageResponse pageResponse=articleService.queryByPageAndStatus(request.getDraw(),request.getOffset(), request.getPageSize(), 2, request.getSearchMsg());
        List<Article> list=(List<Article>) pageResponse.getData();

        return pageResponse;
    }

    /**
     * 前往文章管理界面（草稿箱）
     */
    @RequestMapping("/draftArticleManage")
    public String draftArticleManage(){
        return "admin/draft";
    }

    /**
     * 获取草稿箱文章的信息
     */
    @PostMapping("/draftArticleInfo")
    @ResponseBody
    public PageResponse draftArticleInfo(@RequestBody PageRequest request){

        request.setSearchMsg(request.getSearchMsg().replace(" ",""));
        if (request.getSearchMsg().equals(""))
            request.setSearchMsg(null);
        PageResponse pageResponse=articleService.queryByPageAndStatus(request.getDraw(),request.getOffset(), request.getPageSize(), 0, request.getSearchMsg());
        List<Article> list=(List<Article>) pageResponse.getData();

        return pageResponse;
    }


    /**
     *前往编辑文章界面
     */
    @RequestMapping("/editArticle")
    public String editArticle(Model model,Integer articleId){
        Article article=articleService.queryById(articleId);
        model.addAttribute("article",article);
        List<Kind> kinds=kindService.queryAll();
        model.addAttribute("kinds",kinds);
        List<Tag> tags=tagService.queryAll();
        model.addAttribute("tags",tags);
        List<Tag> articleTagList=article.getTags();
        //用来设置复选框初始值
        Map<Integer,Integer> map=new HashMap<>();
        articleTagList.forEach(tag -> {
            map.put(tag.getId(),1);
        });
        model.addAttribute("map",map);
        return "admin/editArticle";
    }

    /**
     * 编辑文章
     */
    @RequestMapping("/doEditArticle")
    @ResponseBody
    public String doEditArticle(@RequestBody JSONObject obj){

        List<Integer> tagIdList=obj.getJSONArray("tags").toJavaList(Integer.class);
        ResponseResult result=new ResponseResult();
        Article article=new Article();

        if(articleService.update(obj.getInteger("id"), obj.getString("title"), obj.getString("content"),tagIdList,obj.getInteger("kindId"), obj.getString("introduce"),article.getStatus(),obj.getString("img"))){
            result.setCode(200);
        }else {
            result.setCode(500);
            result.setMessage("错误");
        }
//        result.setCode(500);
//        result.setMessage("cw");
        return JSONObject.toJSONString(result);
    }

    /**
     * 将文章放入回收站
     */
    @RequestMapping("/deleteLight")
    @ResponseBody
    public String deleteLight(Integer articleId){

        ResponseResult result=new ResponseResult();
        Article article=articleService.queryById(articleId);
        article.setStatus(2);
        if (articleService.update(article)){
            result.setCode(200);
        }else {
            result.setCode(500);
            result.setMessage("未知错误");
        }
        return JSONObject.toJSONString(result);
    }

    /**
     * 永久删除文章
     */
    @RequestMapping("/deleteStrong")
    @ResponseBody
    public String deleteStrong(Integer articleId){
        ResponseResult result=new ResponseResult();
        if (articleService.deleteById(articleId)){
            result.setCode(200);
        }else {
            result.setCode(500);
            result.setMessage("未知错误");
        }
        return JSONObject.toJSONString(result);
    }

    /**
     * 清空回收站
     */
    @RequestMapping("/clearRecyleBin")
    @ResponseBody
    public String clearRecyleBin(){
        articleService.clearRecyleBin();
        ResponseResult result=new ResponseResult();
        result.setCode(200);
        return JSONObject.toJSONString(result);
    }

    /**
     * 从回收站恢复数据
     */
    @RequestMapping("/restore")
    @ResponseBody
    public String restore(@RequestParam("articleId") Integer articleId,@RequestParam("wantedStatus") Integer wantedStatus){
        Article article=articleService.queryById(articleId);
        article.setStatus(wantedStatus);
        articleService.update(article);
        ResponseResult result=new ResponseResult();
        result.setCode(200);
        return JSONObject.toJSONString(result);
    }

    /**
     * 草稿箱发布文章
     */
    @RequestMapping("/publishFromDraft")
    @ResponseBody
    public String publishFromDraft(Integer id){
        Article article=articleService.queryById(id);
        article.setStatus(1);
        article.setPublishTime(new Date());
        ResponseResult result=new ResponseResult();
        if(articleService.update(article)){
            result.setCode(200);
        }else {
            result.setMessage("发布失败");
            result.setCode(500);
        }
        return JSONObject.toJSONString(result);
    }
}
